// 文件位置：src/components/WorkflowUI.js
import React, { useContext, useState, useCallback, useEffect } from 'react'; // 移除 useEffect，添加 useCallback
import Grid from '@mui/material/Grid';
import Paper from '@mui/material/Paper';
import Button from '@mui/material/Button';
import StepUI from './StepUI';
import WorkflowContext from 'contexts/WorkflowContext';
import ModuleModal from 'components/ui-component/extended/ModuleModal';
import SelectModule from 'components/ui-component/extended/Workflow/SelectModule';
import { fetchAllWorkflows, fetchWorkflowDetailsById, errTest, fetchSingleModuleConfig, renameWorkflow } from 'service/workflowService';
import Input from '@mui/material/Input';
import SkeletonChartCard from 'components/ui-component/cards/Skeleton/TotalGrowthBarChart';
import { WorkflowControls } from './Sub/WorkflowControls'; // 导入封装好的控制按钮组件
import { useAlertSnackbar } from 'utils/alertSnackbar';
import { useRouter } from 'next/router';
// 抽象出控制按钮
const ControlButton = React.memo(({ label, action, disabled }) => (
  <Button variant="contained" color="secondary" onClick={action} disabled={disabled} sx={{ mx: 1 }}>
    {label}
  </Button>
));

const WorkflowUI = ({ defaultWorkflowId }) => {
  const [isWorkflowLoading, setWorkflowLoading] = useState(true);
  const [workflowName, setWorkflowName] = useState('工作流程');
  const [originalWorkflowName, setOriginalWorkflowName] = useState(''); // 新增：用于追踪原始工作流名称
  const {
    initDefaultRawSteps,
    fetchDataForModules,
    transformedSteps,
    insertStep,
    removeStep,
    summarizeAndSendData,
    mapServerDataToClient
  } = useContext(WorkflowContext);
  const alertSnackbar = useAlertSnackbar();
  const router = useRouter();
  async function loadInitialWorkflowData() {
    if (defaultWorkflowId != null) {
      try {
        const defaultWorkflowData = await fetchWorkflowDetailsById(defaultWorkflowId);
        const defaultWorkflow = defaultWorkflowData.data;
        // console.log('获取到的默认工作流程:', defaultWorkflow);
        // 新添加的代码：遍历 steps 数组，根据每一项的 name 属性获取详细配置
        // 新增：初始化工作流名称
        if (defaultWorkflow.nameCn) {
          setWorkflowName(defaultWorkflow.nameCn);
        }
        if (defaultWorkflow.steps && Array.isArray(defaultWorkflow.steps)) {
          const stepsWithConfig = await Promise.all(
            defaultWorkflow.steps.map(async (step) => {
              const config = await fetchSingleModuleConfig(step.name);
              return {
                ...step,
                config // 添加获取到的配置
              };
            })
          );
          const configArray = stepsWithConfig.map((step) => step.config.data);
          console.dir(configArray);
          const newSteps = mapServerDataToClient(defaultWorkflow.steps, configArray);
          initDefaultRawSteps(newSteps);
        }
      } catch (error) {
        // 你的全局异常过滤器应该能处理这里的错误
        console.log('ERROR', error);
        setWorkflowLoading(false);
        alertSnackbar('获取 workflow 详情失败.跳转到创建页面', {
          alert: { color: 'error' },
          autoClose: 2000
        });
        // 调试模式下不跳转
        // router.push('/workflow/create');
      }
    } else {
      setWorkflowLoading(false);
    }
  }
  useEffect(() => {
    loadInitialWorkflowData();
  }, []); //

  useEffect(() => {
    // console.log('555:WorkflowContext.transformedSteps数据发生变化', transformedSteps);
    if (transformedSteps && transformedSteps.length > 0) {
      setWorkflowLoading(false); // 当 transformedSteps 有数据后，设置 isWorkflowLoading 为 false
    }
  }, [transformedSteps]); // 当 transformedSteps 发生变化时触发

  // 添加一个状态来控制 ModuleModal 的显示和隐藏
  const [isModuleModalOpen, setModuleModalOpen] = useState(false);

  const openModuleModal = useCallback(() => setModuleModalOpen(true), []); // 使用 useCallback

  // 这两个函数千万不要useCallback，会导致无法读取数据
  const handleSaveWorkflow = () => {
    console.log('保存工作流的逻辑在这里', transformedSteps);
    // console.clear();
    summarizeAndSendData();
  };
  // 新增一个函数来处理创建工作流
  const handleCreateWorkflow = () => {
    console.log('创建工作流的逻辑在这里', transformedSteps);
    // console.clear();
    summarizeAndSendData();
  };

  // 初始化 originalWorkflowName
  useEffect(() => {
    setOriginalWorkflowName(workflowName);
  }, [workflowName]);
  // 更改工作流名称
  const handleInputChange = useCallback(
    async (e) => {
      if (defaultWorkflowId != null) {
        const newName = e.target.value;
        console.log('工作流名称:', newName);

        if (newName !== originalWorkflowName) {
          const { data, error } = await renameWorkflow(defaultWorkflowId, newName); // 修改：改名
          if (error) {
            console.error(`工作流改名失败：${error}`);
            return;
          }
          console.log('工作流改名成功:', data);
          setOriginalWorkflowName(newName); // 修改：更新原始工作流名称
        }
      } else {
        setWorkflowName(e.target.value); // 没有 defaultWorkflowId 时，只需要保存名称即可
      }
    },
    [originalWorkflowName, defaultWorkflowId]
  );

  // 关闭 ModuleModal 的函数
  const closeModuleModal = useCallback(() => setModuleModalOpen(false), []); // 使用 useCallback

  // 你原来的逻辑
  const fetchWorkflows = async () => {
    const workflowListResult = await fetchAllWorkflows();
    // 错误处理
    if (workflowListResult.error) {
      console.error('获取工作流列表失败:', workflowListResult.error);
      return;
    }
    const workflowList = workflowListResult.data;
    // 使用 Promise.all 并行获取所有工作流的详细信息
    const workflowDetails = await Promise.all(
      workflowList.map(async (workflow) => {
        const workflowId = workflow.id;
        return fetchWorkflowDetailsById(workflowId);
      })
    );
    // 打印详细信息
    workflowList.forEach((workflow, index) => {
      console.log(`Detail of workflow ${workflow.id}:`, workflow);
    });
  };

  // 修改后的错误测试
  const testError = async () => {
    const result = await errTest();

    // 错误处理
    if (result.error) {
      console.error('错误测试失败:', result.error);
      return;
    }
    console.log('result', result.data);
  };

  const handleModuleSelected = async (moduleName) => {
    const result = await fetchSingleModuleConfig(moduleName);
    // console.log('handleModuleSelected', moduleName, result);
    if (result.error) {
      console.error('发生错误:', result.error);
      return;
    }
    console.log('111:WorkflowUI.插入步骤', result.data);
    insertStep(result.data);
    setModuleModalOpen(false);
  };

  const removeStepHandler = (uniqueIndex) => () => removeStep(uniqueIndex);
  return (
    <>
      {isWorkflowLoading ? (
        <SkeletonChartCard /> // 当数据还在加载时，展示 Skeleton
      ) : (
        <Grid container spacing={3}>
          <Grid item xs={12}>
            <Input
              type="text"
              defaultValue={workflowName} // 修改：使用 workflowName 作为默认值
              fullWidth
              onBlur={handleInputChange} // 当输入框失去焦点时触发 handleInputChange
            />
          </Grid>
          <Grid item xs={12}>
            <WorkflowControls
              handleSelectModule={openModuleModal}
              handleWorkflowAction={defaultWorkflowId ? handleSaveWorkflow : handleCreateWorkflow}
              handleWorkflowLabel={defaultWorkflowId ? '保存工作流' : '创建工作流'}
              fetchWorkflows={fetchWorkflows}
              testError={testError}
            />
            <ModuleModal open={isModuleModalOpen} onClose={closeModuleModal}>
              <SelectModule onModuleSelected={handleModuleSelected} />
            </ModuleModal>
          </Grid>
          {transformedSteps.map((step, index) => (
            <Grid item xs={12} key={step.pUniqueIndex}>
              <Paper elevation={3} sx={{ p: 2, display: 'flex', alignItems: 'center' }}>
                <StepUI step={step} />
                <ControlButton label="删除" action={removeStepHandler(step.pUniqueIndex)} disabled={index === 0} />
              </Paper>
            </Grid>
          ))}
        </Grid>
      )}
    </>
  );
};

export default WorkflowUI;
